// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化点赞功能
    initLikeButtons();
    // 初始化排序功能
    initSorting();
    // 初始化筛选功能
    initFilters();
    // 初始化搜索功能
    initSearch();
    // 页面加载时获取帖子列表
    loadPosts();
    // 页面加载时获取用户信息
    loadUserProfile();
});

// 点赞功能
function initLikeButtons() {
    const likeButtons = document.querySelectorAll('.like-btn');
    
    likeButtons.forEach(button => {
        button.addEventListener('click', async function() {
            const postId = this.dataset.postId;
            const likeCount = this.querySelector('.like-count');
            
            // 检查用户是否已登录
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录后再进行点赞操作');
                return;
            }
            
            try {
                console.log('发送点赞请求，帖子ID:', postId);
                
                // 发送点赞请求到后端
                const response = await fetch(`http://localhost:3000/api/posts/${postId}/like`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                console.log('点赞响应状态:', response.status);
                
                if (response.ok) {
                    const data = await response.json();
                    console.log('点赞响应数据:', data);
                    console.log('响应数据类型:', typeof data);
                    console.log('响应数据键:', Object.keys(data));
                    console.log('data.data:', data.data);
                    
                    if (data.success && data.data && typeof data.data.likeCount !== 'undefined') {
                        // 更新点赞数量
                        likeCount.textContent = data.data.likeCount;
                        
                        // 添加点赞动画效果
                        this.style.transform = 'scale(1.2)';
                        setTimeout(() => {
                            this.style.transform = 'scale(1)';
                        }, 200);
                        
                        // 显示点赞成功提示
                        showLikeSuccess();
                    } else {
                        console.error('点赞响应格式错误:', data);
                        console.error('data.success:', data.success);
                        console.error('data.data:', data.data);
                        console.error('data.data.likeCount:', data.data ? data.data.likeCount : 'undefined');
                        alert('点赞失败：响应格式错误');
                    }
                } else {
                    const errorData = await response.json();
                    console.error('点赞失败:', errorData);
                    alert(errorData.message || '点赞失败，请稍后重试');
                }
            } catch (error) {
                console.error('点赞请求出错:', error);
                alert('网络连接错误，请稍后重试');
            }
        });
    });
}

// 显示点赞成功提示
function showLikeSuccess() {
    // 创建一个临时的成功提示
    const successTip = document.createElement('div');
    successTip.className = 'like-success-tip';
    successTip.innerHTML = '<i class="fas fa-heart"></i> 点赞成功！';
    successTip.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(220, 53, 69, 0.9);
        color: white;
        padding: 10px 20px;
        border-radius: 20px;
        font-size: 14px;
        z-index: 9999;
        animation: fadeInOut 2s ease;
    `;
    
    document.body.appendChild(successTip);
    
    // 2秒后移除提示
    setTimeout(() => {
        if (successTip.parentNode) {
            successTip.parentNode.removeChild(successTip);
        }
    }, 2000);
}

// 排序功能
function initSorting() {
    const sortSelect = document.getElementById('sort-select');
    
    sortSelect.addEventListener('change', async function() {
        const sortType = this.value;
        await loadPosts(sortType);
    });
}

// 筛选功能
function initFilters() {
    const typeSelect = document.getElementById('type-select');
    const categorySelect = document.getElementById('category-select');
    
    // 监听类型筛选变化
    typeSelect.addEventListener('change', async function() {
        await applyFilters();
    });
    
    // 监听分类筛选变化
    categorySelect.addEventListener('change', async function() {
        await applyFilters();
    });
}

// 应用筛选条件
async function applyFilters() {
    const type = document.getElementById('type-select').value;
    const category = document.getElementById('category-select').value;
    const sort = document.getElementById('sort-select').value;
    
    await loadPosts(sort, type, category);
}

// 加载帖子列表
async function loadPosts(sort = 'latest', type = 'all', category = 'all', page = 1) {
    try {
        console.log('开始加载帖子列表...', { sort, type, category, page });
        
        // 构建查询参数
        const params = new URLSearchParams({
            sort,
            page
        });
        if (type && type !== 'all') params.append('post_type', type);
        if (category && category !== 'all') params.append('category', category);
        
        const apiUrl = `http://localhost:3000/api/posts?${params.toString()}`;
        console.log('API请求URL:', apiUrl);
        
        // 发送请求获取帖子列表
        const response = await fetch(apiUrl);
        
        console.log('API响应状态:', response.status);
        
        if (response.ok) {
            const data = await response.json();
            console.log('API响应数据:', data);
            
            if (data.success && data.data && data.data.length > 0) {
                // 直接使用API返回的帖子数据
                updatePostList(data.data);
                // 重新初始化点赞按钮
                initLikeButtons();
            } else {
                showNoPosts();
            }
        } else {
            const errorText = await response.text();
            console.error('API响应错误:', response.status, errorText);
            showError('获取帖子列表失败');
        }
    } catch (error) {
        console.error('加载帖子列表出错:', error);
        showError('网络连接错误，请检查服务器状态');
    }
}

function showNoPosts() {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = `
        <div class="empty-state">
            <i class="fas fa-file-alt"></i>
            <p>暂无帖子数据</p>
            <button id="loadPostsBtn" class="load-posts-btn">重新加载</button>
        </div>
    `;
    const loadBtn = document.getElementById('loadPostsBtn');
    if (loadBtn) loadBtn.onclick = () => applyFilters();
}

function showError(msg) {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = `
        <div class="post-error">
            <i class="fas fa-exclamation-triangle"></i>
            <p>${msg}</p>
            <button id="retryLoadBtn" class="load-posts-btn">重新加载</button>
        </div>
    `;
    const retryBtn = document.getElementById('retryLoadBtn');
    if (retryBtn) retryBtn.onclick = () => applyFilters();
}

// 更新帖子列表
function updatePostList(posts) {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = ''; // 清空现有列表
    
    posts.forEach(post => {
        const postElement = createPostElement(post);
        postList.appendChild(postElement);
    });
}

// 创建帖子元素
function createPostElement(post) {
    const article = document.createElement('article');
    article.className = 'post-card';
    
    // 生成帖子类型徽章
    const typeBadgeClass = getTypeBadgeClass(post.post_type);
    const typeBadgeText = post.post_type || '帖子';
    
    // 生成内容预览
    const contentPreview = post.content ? 
        (post.content.length > 100 ? post.content.substring(0, 100) + '...' : post.content) : 
        '帖子内容预览...';
    
    // 生成作者信息
    const authorName = post.author ? post.author.nickname : '用户';
    const authorAvatar = post.author ? post.author.avatar : 'images/avatar1.png';
    
    // 生成时间信息
    const timeText = post.create_time ? formatTime(post.create_time) : '刚刚';
    
    article.innerHTML = `
        <div class="post-header">
            <div class="post-type">
                <span class="type-badge ${typeBadgeClass}">${typeBadgeText}</span>
            </div>
            <h2 class="post-title">${post.title}</h2>
        </div>
        <div class="post-content">
            <p class="post-preview">${contentPreview}</p>
        </div>
        <div class="post-footer">
            <div class="post-meta">
                <span class="author">
                    <img src="${authorAvatar}" alt="作者头像">
                    <span>${authorName}</span>
                </span>
                <span class="time"><i class="far fa-clock"></i> ${timeText}</span>
                <span class="views"><i class="far fa-eye"></i> ${formatNumber(post.view_count || 0)}</span>
                <span class="comments"><i class="far fa-comment"></i> ${formatNumber(post.comment_count || 0)}</span>
            </div>
            <div class="post-actions">
                <button class="like-btn" data-post-id="${post.post_id}">
                    <i class="far fa-heart"></i>
                    <span class="like-count">${formatNumber(post.like_count || 0)}</span>
                </button>
            </div>
        </div>
    `;
    
    return article;
}

// 获取帖子类型徽章样式类
function getTypeBadgeClass(postType) {
    switch (postType) {
        case '攻略':
            return 'guide';
        case '讨论':
            return 'discussion';
        case '视频':
            return 'video';
        case '资讯':
            return 'news';
        default:
            return '';
    }
}

// 更新分页
function updatePagination(pagination) {
    const paginationElement = document.querySelector('.pagination');
    if (!paginationElement) return;
    
    const pageNumbers = paginationElement.querySelector('.page-numbers');
    if (!pageNumbers) return;
    
    let pages = '';
    for (let i = 1; i <= pagination.totalPages; i++) {
        if (i === 1 || i === pagination.totalPages || (i >= pagination.currentPage - 2 && i <= pagination.currentPage + 2)) {
            pages += `<span class="${i === pagination.currentPage ? 'active' : ''}" onclick="loadPosts('${document.getElementById('sort-select').value}', '${document.getElementById('type-select').value}', '${document.getElementById('category-select').value}', ${i})">${i}</span>`;
        } else if (i === pagination.currentPage - 3 || i === pagination.currentPage + 3) {
            pages += '<span>...</span>';
        }
    }
    
    pageNumbers.innerHTML = pages;
}

// 工具函数
function formatTime(timestamp) {
    if (!timestamp) return '未知时间';
    
    const now = new Date();
    const postTime = new Date(timestamp);
    const diff = now - postTime;
    
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (minutes < 60) {
        return `${minutes}分钟前`;
    } else if (hours < 24) {
        return `${hours}小时前`;
    } else if (days < 7) {
        return `${days}天前`;
    } else {
        return postTime.toLocaleDateString('zh-CN');
    }
}

function formatNumber(num) {
    if (!num) return '0';
    if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'k';
    }
    return num.toString();
}

// 搜索功能
function initSearch() {
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const searchTitle = document.getElementById('search-title');
    const searchContent = document.getElementById('search-content');
    
    // 搜索按钮点击事件
    searchBtn.addEventListener('click', async function() {
        await performSearch();
    });
    
    // 回车键搜索
    searchInput.addEventListener('keypress', async function(e) {
        if (e.key === 'Enter') {
            await performSearch();
        }
    });
    
    // 搜索选项变化时重新搜索
    searchTitle.addEventListener('change', async function() {
        if (searchInput.value.trim()) {
            await performSearch();
        }
    });
    
    searchContent.addEventListener('change', async function() {
        if (searchInput.value.trim()) {
            await performSearch();
        }
    });
}

// 执行搜索
async function performSearch() {
    const searchInput = document.getElementById('search-input');
    const searchTitle = document.getElementById('search-title');
    const searchContent = document.getElementById('search-content');
    
    const searchTerm = searchInput.value.trim();
    
    if (!searchTerm) {
        // 如果搜索词为空，清除搜索并显示所有帖子
        clearSearch();
        return;
    }
    
    // 检查是否至少选择了一个搜索选项
    if (!searchTitle.checked && !searchContent.checked) {
        alert('请至少选择一个搜索范围（标题或内容）');
        return;
    }
    
    try {
        // 构建搜索参数
        const params = new URLSearchParams({
            search: searchTerm,
            search_title: searchTitle.checked ? '1' : '0',
            search_content: searchContent.checked ? '1' : '0',
            sort: document.getElementById('sort-select').value,
            post_type: document.getElementById('type-select').value,
            category: document.getElementById('category-select').value
        });
        
        const apiUrl = `http://localhost:3000/api/posts/search?${params.toString()}`;
        console.log('搜索API请求URL:', apiUrl);
        
        // 显示加载状态
        showSearchLoading();
        
        // 发送搜索请求
        const response = await fetch(apiUrl);
        
        if (response.ok) {
            const data = await response.json();
            console.log('搜索响应数据:', data);
            
            if (data.success && data.data && data.data.length > 0) {
                updatePostList(data.data);
                showSearchResults(data.data.length, searchTerm);
                // 重新初始化点赞按钮
                initLikeButtons();
            } else {
                showNoSearchResults(searchTerm);
            }
        } else {
            const errorText = await response.text();
            console.error('搜索API响应错误:', response.status, errorText);
            showSearchError('搜索失败，请稍后重试');
        }
    } catch (error) {
        console.error('搜索请求出错:', error);
        showSearchError('网络连接错误，请检查服务器状态');
    }
}

// 显示搜索加载状态
function showSearchLoading() {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = `
        <div class="search-loading">
            <i class="fas fa-spinner fa-spin"></i>
            <p>正在搜索...</p>
        </div>
    `;
}

// 显示搜索结果信息
function showSearchResults(resultCount, searchTerm) {
    const postList = document.querySelector('.post-list');
    
    // 在帖子列表前插入搜索结果信息
    const resultsInfo = document.createElement('div');
    resultsInfo.className = 'search-results-info';
    resultsInfo.innerHTML = `
        <div class="results-count">
            <i class="fas fa-search"></i>
            找到 ${resultCount} 条与"${searchTerm}"相关的帖子
        </div>
        <button class="clear-search" onclick="clearSearch()">
            <i class="fas fa-times"></i> 清除搜索
        </button>
    `;
    
    // 如果已经有搜索结果信息，则替换它
    const existingInfo = document.querySelector('.search-results-info');
    if (existingInfo) {
        existingInfo.remove();
    }
    
    postList.insertBefore(resultsInfo, postList.firstChild);
}

// 显示无搜索结果
function showNoSearchResults(searchTerm) {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = `
        <div class="search-results-info">
            <div class="results-count">
                <i class="fas fa-search"></i>
                未找到与"${searchTerm}"相关的帖子
            </div>
            <button class="clear-search" onclick="clearSearch()">
                <i class="fas fa-times"></i> 清除搜索
            </button>
        </div>
        <div class="empty-state">
            <i class="fas fa-search"></i>
            <p>没有找到相关帖子</p>
            <p style="font-size: 14px; color: #666; margin-top: 10px;">
                尝试使用不同的关键词或检查拼写
            </p>
            <button class="load-posts-btn" onclick="clearSearch()">返回全部帖子</button>
        </div>
    `;
}

// 显示搜索错误
function showSearchError(message) {
    const postList = document.querySelector('.post-list');
    postList.innerHTML = `
        <div class="search-results-info">
            <div class="results-count">
                <i class="fas fa-exclamation-triangle"></i>
                搜索出错
            </div>
            <button class="clear-search" onclick="clearSearch()">
                <i class="fas fa-times"></i> 清除搜索
            </button>
        </div>
        <div class="post-error">
            <i class="fas fa-exclamation-triangle"></i>
            <p>${message}</p>
            <button class="load-posts-btn" onclick="clearSearch()">返回全部帖子</button>
        </div>
    `;
}

// 清除搜索
async function clearSearch() {
    const searchInput = document.getElementById('search-input');
    const searchTitle = document.getElementById('search-title');
    const searchContent = document.getElementById('search-content');
    
    // 清空搜索输入框
    searchInput.value = '';
    
    // 确保搜索选项被选中
    if (!searchTitle.checked && !searchContent.checked) {
        searchTitle.checked = true;
        searchContent.checked = true;
    }
    
    // 移除搜索结果信息
    const resultsInfo = document.querySelector('.search-results-info');
    if (resultsInfo) {
        resultsInfo.remove();
    }
    
    // 重新加载所有帖子
    await applyFilters();
}

// 页面加载时获取用户信息
async function loadUserProfile() {
    const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
    const userId = user.userId;
    if (!userId) return;

    try {
        const response = await fetch(`http://localhost:8080/userapi/users/profile/${userId}`);
        if (response.ok) {
            const result = await response.json();
            const userData = result.user || result;

            // 更新头像
            document.querySelectorAll('.user-avatar img').forEach(img => {
                img.src = userData.avatar || 'images/default-avatar.png';
            });
            // 更新用户名
            document.querySelectorAll('.user-info h4').forEach(h4 => {
                h4.textContent = userData.nickname || '用户名';
            });
            // 更新UID
            document.querySelectorAll('.user-info p').forEach(p => {
                p.textContent = `UID: ${userData.gameUid || '未绑定'}`;
            });
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
    }
} 